package com.alex.wechat.component.codemgr.controller;

import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;

import org.apache.log4j.Logger;
import org.jeecgframework.core.beanvalidator.BeanValidators;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.ExceptionUtil;
import org.jeecgframework.core.util.MyBeanUtils;
import org.jeecgframework.core.util.ResourceUtil;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.vo.NormalExcelConstants;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.tag.vo.datatable.SortDirection;
import org.jeecgframework.web.system.service.SystemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.UriComponentsBuilder;

import com.alex.wechat.app.account.entity.WxAppAccountEntity;
import com.alex.wechat.app.config.WxAppContext;
import com.alex.wechat.component.codemgr.entity.AuditState;
import com.alex.wechat.component.codemgr.entity.WxCodeUploadMgrEntity;
import com.alex.wechat.component.codemgr.service.WxCodeUploadMgrServiceI;
import com.gomore.jeecg.common.ServiceException;

import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.common.util.JsonMapper;
import me.chanjar.weixin.component.api.WxCompService;
import me.chanjar.weixin.component.api.app.WxCompMaCodeService;
import me.chanjar.weixin.component.bean.code.ExtJson;
import me.chanjar.weixin.component.bean.code.ExtJson.Ext;
import me.chanjar.weixin.component.bean.code.WxAppAudit;
import me.chanjar.weixin.component.bean.code.WxAppCategory;
import me.chanjar.weixin.component.bean.code.WxAppCode;

/**
 * @Title: Controller
 * @Description: 代码管理
 * @author onlineGenerator
 * @date 2017-05-25 15:26:25
 * @version V1.0
 *
 */
@Controller
@RequestMapping("/wxCodeUploadMgrController")
public class WxCodeUploadMgrController extends BaseController {
  /**
   * Logger for this class
   */
  private static final Logger logger = Logger.getLogger(WxCodeUploadMgrController.class);

  @Autowired
  private WxCodeUploadMgrServiceI wxCodeUploadMgrService;
  @Autowired
  private SystemService systemService;
  @Autowired
  private Validator validator;
  @Autowired
  private WxCompService wxComponentService;

  /**
   * 代码管理列表 页面跳转
   * 
   * @return
   */
  @RequestMapping(params = "list")
  public ModelAndView list(HttpServletRequest request) {
    return new ModelAndView("com/gomore/wechat/component/codemgr/wxCodeUploadMgrList");
  }

  /**
   * easyui AJAX请求数据
   * 
   * @param request
   * @param response
   * @param dataGrid
   * @param user
   */

  @RequestMapping(params = "datagrid")
  public void datagrid(WxCodeUploadMgrEntity wxCodeUploadMgr, HttpServletRequest request,
      HttpServletResponse response, DataGrid dataGrid) {
    CriteriaQuery cq = new CriteriaQuery(WxCodeUploadMgrEntity.class, dataGrid);
    // 查询条件组装器
    org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, wxCodeUploadMgr,
        request.getParameterMap());
    try {
      // 自定义追加查询条件
      cq.addOrder("createDate", SortDirection.desc);
    } catch (Exception e) {
      throw new BusinessException(e.getMessage());
    }
    cq.add();
    this.wxCodeUploadMgrService.getDataGridReturn(cq, true);
    TagUtil.datagrid(response, dataGrid);
  }

  /**
   * 删除代码管理
   * 
   * @return
   */
  @RequestMapping(params = "doDel")
  @ResponseBody
  public AjaxJson doDel(WxCodeUploadMgrEntity wxCodeUploadMgr, HttpServletRequest request) {
    String message = null;
    AjaxJson j = new AjaxJson();
    wxCodeUploadMgr = systemService.getEntity(WxCodeUploadMgrEntity.class, wxCodeUploadMgr.getId());
    message = "代码管理删除成功";
    try {
      wxCodeUploadMgrService.delete(wxCodeUploadMgr);
      systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
    } catch (Exception e) {
      e.printStackTrace();
      message = "代码管理删除失败";
      throw new BusinessException(e.getMessage());
    }
    j.setMsg(message);
    return j;
  }

  /**
   * 批量删除代码管理
   * 
   * @return
   */
  @RequestMapping(params = "doBatchDel")
  @ResponseBody
  public AjaxJson doBatchDel(String ids, HttpServletRequest request) {
    String message = null;
    AjaxJson j = new AjaxJson();
    message = "代码管理删除成功";
    try {
      for (String id : ids.split(",")) {
        WxCodeUploadMgrEntity wxCodeUploadMgr = systemService.getEntity(WxCodeUploadMgrEntity.class,
            id);
        wxCodeUploadMgrService.delete(wxCodeUploadMgr);
        systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
      }
    } catch (Exception e) {
      e.printStackTrace();
      message = "代码管理删除失败";
      throw new BusinessException(e.getMessage());
    }
    j.setMsg(message);
    return j;
  }

  /**
   * 添加代码管理
   * 
   * @param
   * @return
   */
  @RequestMapping(params = "doAdd")
  @ResponseBody
  public AjaxJson doAdd(WxCodeUploadMgrEntity wxCodeUploadMgr, HttpServletRequest request) {
    String message = null;
    AjaxJson j = new AjaxJson();
    message = "代码提交成功";
    try {
      if (StringUtil.isEmpty(wxCodeUploadMgr.getAppId())) {
        throw new ServiceException();
      }

      WxAppContext.setAppId(wxCodeUploadMgr.getAppId());
      WxAppAccountEntity account = WxAppContext.getAppAccount();
      WxCompMaCodeService wxComponentAppCodeService = wxComponentService.getMaServiceDelegate().getMaCodeService();
      WxAppCode appCode = new WxAppCode();

      // 自定义参数
      Ext ext = new Ext();
      ext.setAppId(wxCodeUploadMgr.getAppId());
      ext.setBaseUrl(ResourceUtil.getConfigByName("domain") + "/app");
      ext.setVersion(wxCodeUploadMgr.getUserVersion());
      ext.setServiceTel(account.getParterTelephone());

      // ext.json
      ExtJson extJson = new ExtJson();
      extJson.setExtAppid(wxCodeUploadMgr.getAppId());
      extJson.setExt(ext);
      extJson.setExtEnable(true);

      appCode.setExtJson(JsonMapper.defaultMapper().toJson(extJson));
      appCode.setUserDesc(wxCodeUploadMgr.getUserDesc());
      appCode.setUserVersion(wxCodeUploadMgr.getUserVersion());
      appCode.setTemplateId(wxCodeUploadMgr.getTemplateId());
      wxComponentAppCodeService.commit(appCode);
      wxCodeUploadMgr.setStatus(AuditState.SUBMITED);
      wxCodeUploadMgrService.save(wxCodeUploadMgr);
      systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
    } catch (Exception e) {
      e.printStackTrace();
      message = "代码提交失败";
      throw new BusinessException(e.getMessage());
    }
    j.setMsg(message);
    return j;
  }

  /**
   * 更新代码管理
   * 
   * @param ids
   * @return
   */
  @RequestMapping(params = "doUpdate")
  @ResponseBody
  public AjaxJson doUpdate(WxCodeUploadMgrEntity wxCodeUploadMgr, HttpServletRequest request) {
    String message = null;
    AjaxJson j = new AjaxJson();
    message = "代码管理更新成功";
    WxCodeUploadMgrEntity t = wxCodeUploadMgrService.get(WxCodeUploadMgrEntity.class,
        wxCodeUploadMgr.getId());
    try {
      MyBeanUtils.copyBeanNotNull2Bean(wxCodeUploadMgr, t);
      wxCodeUploadMgrService.saveOrUpdate(t);
      systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
    } catch (Exception e) {
      e.printStackTrace();
      message = "代码管理更新失败";
      throw new BusinessException(e.getMessage());
    }
    j.setMsg(message);
    return j;
  }

  /**
   * 代码管理新增页面跳转
   * 
   * @return
   */
  @RequestMapping(params = "goAdd")
  public ModelAndView goAdd(WxCodeUploadMgrEntity wxCodeUploadMgr, HttpServletRequest req) {
    if (StringUtil.isNotEmpty(wxCodeUploadMgr.getId())) {
      wxCodeUploadMgr = wxCodeUploadMgrService.getEntity(WxCodeUploadMgrEntity.class,
          wxCodeUploadMgr.getId());
      req.setAttribute("wxCodeUploadMgrPage", wxCodeUploadMgr);
    }
    return new ModelAndView("com/gomore/wechat/component/codemgr/wxCodeUploadMgr-add");
  }

  /**
   * 代码管理编辑页面跳转
   * 
   * @return
   */
  @RequestMapping(params = "goUpdate")
  public ModelAndView goUpdate(WxCodeUploadMgrEntity wxCodeUploadMgr, HttpServletRequest req) {
    if (StringUtil.isNotEmpty(wxCodeUploadMgr.getId())) {
      wxCodeUploadMgr = wxCodeUploadMgrService.getEntity(WxCodeUploadMgrEntity.class,
          wxCodeUploadMgr.getId());
      req.setAttribute("wxCodeUploadMgrPage", wxCodeUploadMgr);
    }
    return new ModelAndView("com/gomore/wechat/component/codemgr/wxCodeUploadMgr-update");
  }

  /**
   * 导入功能跳转
   * 
   * @return
   */
  @RequestMapping(params = "upload")
  public ModelAndView upload(HttpServletRequest req) {
    req.setAttribute("controller_name", "wxCodeUploadMgrController");
    return new ModelAndView("common/upload/pub_excel_upload");
  }

  /**
   * 导出excel
   * 
   * @param request
   * @param response
   */
  @RequestMapping(params = "exportXls")
  public String exportXls(WxCodeUploadMgrEntity wxCodeUploadMgr, HttpServletRequest request,
      HttpServletResponse response, DataGrid dataGrid, ModelMap modelMap) {
    CriteriaQuery cq = new CriteriaQuery(WxCodeUploadMgrEntity.class, dataGrid);
    org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, wxCodeUploadMgr,
        request.getParameterMap());
    List<WxCodeUploadMgrEntity> wxCodeUploadMgrs = this.wxCodeUploadMgrService
        .getListByCriteriaQuery(cq, false);
    modelMap.put(NormalExcelConstants.FILE_NAME, "代码管理");
    modelMap.put(NormalExcelConstants.CLASS, WxCodeUploadMgrEntity.class);
    modelMap.put(NormalExcelConstants.PARAMS, new ExportParams("代码管理列表",
        "导出人:" + ResourceUtil.getSessionUserName().getRealName(), "导出信息"));
    modelMap.put(NormalExcelConstants.DATA_LIST, wxCodeUploadMgrs);
    return NormalExcelConstants.JEECG_EXCEL_VIEW;
  }

  /**
   * 导出excel 使模板
   * 
   * @param request
   * @param response
   */
  @RequestMapping(params = "exportXlsByT")
  public String exportXlsByT(WxCodeUploadMgrEntity wxCodeUploadMgr, HttpServletRequest request,
      HttpServletResponse response, DataGrid dataGrid, ModelMap modelMap) {
    modelMap.put(NormalExcelConstants.FILE_NAME, "代码管理");
    modelMap.put(NormalExcelConstants.CLASS, WxCodeUploadMgrEntity.class);
    modelMap.put(NormalExcelConstants.PARAMS, new ExportParams("代码管理列表",
        "导出人:" + ResourceUtil.getSessionUserName().getRealName(), "导出信息"));
    modelMap.put(NormalExcelConstants.DATA_LIST, new ArrayList());
    return NormalExcelConstants.JEECG_EXCEL_VIEW;
  }

  @SuppressWarnings("unchecked")
  @RequestMapping(params = "importExcel", method = RequestMethod.POST)
  @ResponseBody
  public AjaxJson importExcel(HttpServletRequest request, HttpServletResponse response) {
    AjaxJson j = new AjaxJson();

    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
    for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
      MultipartFile file = entity.getValue();// 获取上传文件对象
      ImportParams params = new ImportParams();
      params.setTitleRows(2);
      params.setHeadRows(1);
      params.setNeedSave(true);
      try {
        List<WxCodeUploadMgrEntity> listWxCodeUploadMgrEntitys = ExcelImportUtil
            .importExcel(file.getInputStream(), WxCodeUploadMgrEntity.class, params);
        for (WxCodeUploadMgrEntity wxCodeUploadMgr : listWxCodeUploadMgrEntitys) {
          wxCodeUploadMgrService.save(wxCodeUploadMgr);
        }
        j.setMsg("文件导入成功！");
      } catch (Exception e) {
        j.setMsg("文件导入失败！");
        logger.error(ExceptionUtil.getExceptionMessage(e));
      } finally {
        try {
          file.getInputStream().close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
    return j;
  }

  @RequestMapping(method = RequestMethod.GET)
  @ResponseBody
  public List<WxCodeUploadMgrEntity> list() {
    List<WxCodeUploadMgrEntity> listWxCodeUploadMgrs = wxCodeUploadMgrService
        .getList(WxCodeUploadMgrEntity.class);
    return listWxCodeUploadMgrs;
  }

  @RequestMapping(value = "/{id}", method = RequestMethod.GET)
  @ResponseBody
  public ResponseEntity<?> get(@PathVariable("id") String id) {
    WxCodeUploadMgrEntity task = wxCodeUploadMgrService.get(WxCodeUploadMgrEntity.class, id);
    if (task == null) {
      return new ResponseEntity(HttpStatus.NOT_FOUND);
    }
    return new ResponseEntity(task, HttpStatus.OK);
  }

  @RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
  @ResponseBody
  public ResponseEntity<?> create(@RequestBody WxCodeUploadMgrEntity wxCodeUploadMgr,
      UriComponentsBuilder uriBuilder) {
    // 调用JSR303 Bean Validator进行校验，如果出错返回含400错误码及json格式的错误信息.
    Set<ConstraintViolation<WxCodeUploadMgrEntity>> failures = validator.validate(wxCodeUploadMgr);
    if (!failures.isEmpty()) {
      return new ResponseEntity(BeanValidators.extractPropertyAndMessage(failures),
          HttpStatus.BAD_REQUEST);
    }

    // 保存
    try {
      wxCodeUploadMgrService.save(wxCodeUploadMgr);
    } catch (Exception e) {
      e.printStackTrace();
      return new ResponseEntity(HttpStatus.NO_CONTENT);
    }
    // 按照Restful风格约定，创建指向新任务的url, 也可以直接返回id或对象.
    String id = wxCodeUploadMgr.getId();
    URI uri = uriBuilder.path("/rest/wxCodeUploadMgrController/" + id).build().toUri();
    HttpHeaders headers = new HttpHeaders();
    headers.setLocation(uri);

    return new ResponseEntity(headers, HttpStatus.CREATED);
  }

  @RequestMapping(value = "/{id}", method = RequestMethod.PUT,
      consumes = MediaType.APPLICATION_JSON_VALUE)
  public ResponseEntity<?> update(@RequestBody WxCodeUploadMgrEntity wxCodeUploadMgr) {
    // 调用JSR303 Bean Validator进行校验，如果出错返回含400错误码及json格式的错误信息.
    Set<ConstraintViolation<WxCodeUploadMgrEntity>> failures = validator.validate(wxCodeUploadMgr);
    if (!failures.isEmpty()) {
      return new ResponseEntity(BeanValidators.extractPropertyAndMessage(failures),
          HttpStatus.BAD_REQUEST);
    }

    // 保存
    try {
      wxCodeUploadMgrService.saveOrUpdate(wxCodeUploadMgr);
    } catch (Exception e) {
      e.printStackTrace();
      return new ResponseEntity(HttpStatus.NO_CONTENT);
    }

    // 按Restful约定，返回204状态码, 无内容. 也可以返回200状态码.
    return new ResponseEntity(HttpStatus.NO_CONTENT);
  }

  @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
  @ResponseStatus(HttpStatus.NO_CONTENT)
  public void delete(@PathVariable("id") String id) {
    wxCodeUploadMgrService.deleteEntityById(WxCodeUploadMgrEntity.class, id);
  }

  /**
   * 提交审核
   * 
   * @param ids
   * @return
   */
  @RequestMapping(params = "submitAudit")
  @ResponseBody
  public AjaxJson submitAudit(HttpServletRequest request) {

    String message = null;
    AjaxJson j = new AjaxJson();
    message = "提交成功";
    String id = request.getParameter("id");
    WxCodeUploadMgrEntity t = wxCodeUploadMgrService.get(WxCodeUploadMgrEntity.class, id);
    try {
      WxCompMaCodeService wxComponentAppCodeService = wxComponentService.getMaServiceDelegate()
          .getMaCodeService();
      WxAppAudit req = getWxAppAudit(t);
      WxAppContext.setAppId(t.getAppId());
      String auditId = wxComponentAppCodeService.submitAudit(req);
      t.setAuditId(auditId);
      t.setStatus(AuditState.AUDITING);
      wxCodeUploadMgrService.saveOrUpdate(t);

      systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
    } catch (Exception e) {
      e.printStackTrace();
      message = "提交失败";
      throw new BusinessException(e.getMessage());
    }
    j.setMsg(message);

    return j;
  }

  // 获取提交审核所需信息
  private WxAppAudit getWxAppAudit(WxCodeUploadMgrEntity t) throws WxErrorException {
    WxAppContext.setAppId(t.getAppId());

    WxCompMaCodeService wxComponentAppCodeService = wxComponentService.getMaServiceDelegate()
        .getMaCodeService();
    WxAppCategory category = null;
    // 类目
    List<WxAppCategory> categories = wxComponentAppCodeService.getCategory();
    if (categories != null && categories.size() > 0) {
      category = categories.get(0);
    } else {
      category = new WxAppCategory();
      category.setFirstClass("生活服务");
      category.setSecondClass("综合生活服务平台");
    }

    String page = null;
    // 页面配置
    List<String> pages = wxComponentAppCodeService.getPage();
    if (pages != null && pages.size() > 0) {
      page = pages.get(0);
    } else {
      page = "pages/discovery/discovery";
    }

    WxAppAudit wxAppAudit = new WxAppAudit();
    wxAppAudit.setAddress(page);
    wxAppAudit.setTag("优惠券");
    wxAppAudit.setFirstClass(category.getFirstClass());
    wxAppAudit.setSecondClass(category.getSecondClass());
    wxAppAudit.setThirdClass(category.getThirdClass());
    wxAppAudit.setTitle("优惠券");

    return wxAppAudit;

  }

  /**
   * 提交发布
   * 
   * @return
   */
  @RequestMapping(params = "publish")
  @ResponseBody
  public AjaxJson publish(HttpServletRequest request) {

    String message = null;
    AjaxJson j = new AjaxJson();
    message = "发布成功";
    String id = request.getParameter("id");
    WxCodeUploadMgrEntity t = wxCodeUploadMgrService.get(WxCodeUploadMgrEntity.class, id);

    try {
      WxCompMaCodeService wxComponentAppCodeService = wxComponentService.getMaServiceDelegate()
          .getMaCodeService();
      WxAppContext.setAppId(t.getAppId());
      wxComponentAppCodeService.release();
      t.setStatus(AuditState.PUBLISED);
      wxCodeUploadMgrService.saveOrUpdate(t);

      systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
    } catch (Exception e) {
      message = "发布失败:" + e.getMessage();
      throw new BusinessException(e.getMessage());
    }
    j.setMsg(message);

    return j;
  }

}
